package freemarker.core;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.etlmaster.executor.utils.LogWriter;

import freemarker.template.TemplateException;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

 /**
 * 计算星期中的第几天的函数
 * 
 * @author wugf
 */
public class DayOfWeekBI extends ExtBuildIn.ExtBuildInModel {
	public String getName() {
		return "dayOfWeek";
	}

	public TemplateModel calculateResult(final String s,
			final Environment env) throws TemplateException {
		return new TemplateMethodModelEx() {
			public Object exec(List args) throws TemplateModelException {
				String format="yyyyMMdd";
				try {
				if(args.size()>0){
					format=args.get(0).toString();
				}
				SimpleDateFormat sdf=new SimpleDateFormat(format);
				
					Date date=sdf.parse(s);
					Calendar ca=Calendar.getInstance();
					ca.setTime(date);
					int dayOfWeek= ca.get(Calendar.DAY_OF_WEEK)-1;
					if(dayOfWeek==0){
						return 7;
					}else{
						return dayOfWeek;
					}
				} catch (Exception e) {
					LogWriter.addLog("ERROR","日期解析异常!{}",e.getMessage());
					throw new TemplateModelException();
				}
			}
		};
	}
}